package com.robot.agent.service;

import com.robot.agent.dao.AgentDao;
import com.robot.agent.pojo.Agent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import util.IdWorker;
import util.UpdateUtil;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * agent服务层
 *
 * @author wuyunbin
 */
@Service
public class AgentService {
    @Autowired
    private AgentDao agentDao;

    @Autowired
    private IdWorker idWorker;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${sys.avatar}")
    private String avatar;
    /**
     * 查询全部列表
     *
     * @return
     */
    public List<Agent> findAll() {
        return agentDao.findAll();
    }

    /**
     * 条件查询+分页
     *
     * @param whereMap
     * @param page
     * @param size
     * @return
     */
    public Page<Agent> findSearch(Map whereMap, int page, int size) {
        Specification<Agent> specification = createSpecification(whereMap);
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return agentDao.findAll(specification, pageRequest);
    }


    /**
     * 条件查询
     *
     * @param whereMap
     * @return
     */
    public List<Agent> findSearch(Map whereMap) {
        Specification<Agent> specification = createSpecification(whereMap);
        return agentDao.findAll(specification);
    }

    /**
     * 根据ID查询实体
     *
     * @param id
     * @return
     */
    public Agent findById(String id) {
        return agentDao.findById(id).orElse(null);
    }

    /**
     * 增加
     *
     * @param agent
     */
    public void add(Agent agent) {
        LocalDateTime now = LocalDateTime.now();
        if("".equals(agent.getAvatar().trim())){
            agent.setAccountName(avatar);
        }
        agent.setCreatedAt(now);
        agent.setUpdatedAt(now);
        agentDao.save(agent);
    }

    /**
     * 修改
     *
     * @param agent
     */
    public void update(Agent agent) {
        Agent agentInDb = findById(agent.getId());
        UpdateUtil.copyNonNullProperties(agent, agentInDb);
        agentInDb.setUpdatedAt(LocalDateTime.now());
        agentDao.save(agentInDb);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void deleteById(String id) {
        agentDao.deleteById(id);
    }

    /**
     * 动态条件构建
     *
     * @param searchMap
     * @return
     */
    private Specification<Agent> createSpecification(Map searchMap) {
        return new Specification<Agent>() {
            @Override
            public Predicate toPredicate(Root<Agent> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                // 代理商id
                String id = "id";
                if (searchMap.get(id) != null && !"".equals(searchMap.get(id))) {
                    predicateList.add(cb.like(root.get(id).as(String.class), "%" + (String) searchMap.get(id) + "%"));
                }
                // 昵称-默认取微信昵称
                String nickname = "nickname";
                if (searchMap.get(nickname) != null && !"".equals(searchMap.get(nickname))) {
                    predicateList.add(cb.like(root.get(nickname).as(String.class), "%" + (String) searchMap.get(nickname) + "%"));
                }
                // 手机号
                String phone = "phone";
                if (searchMap.get(phone) != null && !"".equals(searchMap.get(phone))) {
                    predicateList.add(cb.like(root.get(phone).as(String.class), "%" + (String) searchMap.get(phone) + "%"));
                }
                // 状态 0-禁用 1-启用
                String status = "status";
                if (searchMap.get(status) != null && !"".equals(searchMap.get(status))) {
                    predicateList.add(cb.like(root.get(status).as(String.class), "%" + (String) searchMap.get(status) + "%"));
                }
                // 身份证号码
                String idCard = "idCard";
                if (searchMap.get(idCard) != null && !"".equals(searchMap.get(idCard))) {
                    predicateList.add(cb.like(root.get(idCard).as(String.class), "%" + (String) searchMap.get(idCard) + "%"));
                }
                // 真实姓名
                String realName = "realName";
                if (searchMap.get(realName) != null && !"".equals(searchMap.get(realName))) {
                    predicateList.add(cb.like(root.get(realName).as(String.class), "%" + (String) searchMap.get(realName) + "%"));
                }
                // 实名制状态
                String realNameStatus = "realNameStatus";
                if (searchMap.get(realNameStatus) != null && !"".equals(searchMap.get(realNameStatus))) {
                    predicateList.add(cb.like(root.get(realNameStatus).as(String.class), "%" + (String) searchMap.get(realNameStatus) + "%"));
                }
                // 省份
                String province = "province";
                if (searchMap.get(province) != null && !"".equals(searchMap.get(province))) {
                    predicateList.add(cb.like(root.get(province).as(String.class), "%" + (String) searchMap.get(province) + "%"));
                }
                // 省份id
                String provinceId = "provinceId";
                if (searchMap.get(provinceId) != null && !"".equals(searchMap.get(provinceId))) {
                    predicateList.add(cb.like(root.get(provinceId).as(String.class), "%" + (String) searchMap.get(provinceId) + "%"));
                }
                // 城市
                String city = "city";
                if (searchMap.get(city) != null && !"".equals(searchMap.get(city))) {
                    predicateList.add(cb.like(root.get(city).as(String.class), "%" + (String) searchMap.get(city) + "%"));
                }
                // 城市id
                String cityId = "cityId";
                if (searchMap.get(cityId) != null && !"".equals(searchMap.get(cityId))) {
                    predicateList.add(cb.like(root.get(cityId).as(String.class), "%" + (String) searchMap.get(cityId) + "%"));
                }
                // 区县
                String area = "area";
                if (searchMap.get(area) != null && !"".equals(searchMap.get(area))) {
                    predicateList.add(cb.like(root.get(area).as(String.class), "%" + (String) searchMap.get(area) + "%"));
                }
                // 区县id
                String areaId = "areaId";
                if (searchMap.get(areaId) != null && !"".equals(searchMap.get(areaId))) {
                    predicateList.add(cb.like(root.get(areaId).as(String.class), "%" + (String) searchMap.get(areaId) + "%"));
                }
                // 代理商类型 0-私人 1-公司
                String agentType = "agentType";
                if (searchMap.get(agentType) != null && !"".equals(searchMap.get(agentType))) {
                    predicateList.add(cb.like(root.get(agentType).as(String.class), "%" + (String) searchMap.get(agentType) + "%"));
                }
                // 公司名字
                String companyName = "companyName";
                if (searchMap.get(companyName) != null && !"".equals(searchMap.get(companyName))) {
                    predicateList.add(cb.like(root.get(companyName).as(String.class), "%" + (String) searchMap.get(companyName) + "%"));
                }
                // 营业执照号码
                String businessLicense = "businessLicense";
                if (searchMap.get(businessLicense) != null && !"".equals(searchMap.get(businessLicense))) {
                    predicateList.add(cb.like(root.get(businessLicense).as(String.class), "%" + (String) searchMap.get(businessLicense) + "%"));
                }
                // 开户行名称
                String bankName = "bankName";
                if (searchMap.get(bankName) != null && !"".equals(searchMap.get(bankName))) {
                    predicateList.add(cb.like(root.get(bankName).as(String.class), "%" + (String) searchMap.get(bankName) + "%"));
                }
                // 银行账号
                String bankAccount = "bankAccount";
                if (searchMap.get(bankAccount) != null && !"".equals(searchMap.get(bankAccount))) {
                    predicateList.add(cb.like(root.get(bankAccount).as(String.class), "%" + (String) searchMap.get(bankAccount) + "%"));
                }
                // 户名
                String accountName = "accountName";
                if (searchMap.get(accountName) != null && !"".equals(searchMap.get(accountName))) {
                    predicateList.add(cb.like(root.get(accountName).as(String.class), "%" + (String) searchMap.get(accountName) + "%"));
                }
                // 账户类型
                String accountType = "accountType";
                if (searchMap.get(accountType) != null && !"".equals(searchMap.get(accountType))) {
                    predicateList.add(cb.like(root.get(accountType).as(String.class), "%" + (String) searchMap.get(accountType) + "%"));
                }
                //剔除软删除数据
                String deletedAt = "deletedAt";
                predicateList.add(cb.equal(root.get(deletedAt), cb.nullLiteral(LocalDateTime.class)));

                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
    }


    /**
     * 通过手机号查找
     *
     * @param phone
     * @return
     */
    public Agent findAgentByPhone(String phone) {
        return agentDao.findAgentByPhone(phone);
    }

    /**
     * 通过areaId和status查询agent
     *
     * @param areaId
     * @param status
     * @return
     */
    public Agent findByAreaIdAndStatusAndDeletedAtIsNull(String areaId, String status) {
        return agentDao.findByAreaIdAndStatusAndDeletedAtIsNull(areaId, status);
    }
}